package com.suncnpap.journal.controller;

import com.suncnpap.journal.model.BorrowJournal;
import com.suncnpap.journal.model.BorrowJournalInfo;
import com.suncnpap.journal.model.BorrowJournalRecord;
import com.suncnpap.journal.model.Journal;
import com.suncnpap.journal.model.JournalRegistration;
import com.suncnpap.journal.model.JournalType;
import com.suncnpap.journal.model.ReturnJournal;
import com.suncnpap.journal.service.BorrowJournalRecordService;
import com.suncnpap.journal.service.BorrowJournalService;
import com.suncnpap.journal.service.JournalRegistrationService;
import com.suncnpap.journal.service.JournalService;
import com.suncnpap.journal.service.JournalTypeService;
import com.suncnpap.journal.service.ReturnJournalService;
import com.suncnpap.library.model.BorrowBook;
import com.suncnpap.library.model.BorrowBookInfo;
import com.suncnpap.reader.model.Reader;
import com.suncnpap.reader.model.ReaderType;
import com.suncnpap.reader.service.ReaderService;
import com.suncnpap.reader.service.ReaderTypeService;
import com.suncnpap.statistics.annotation.LogType;
import com.suncnpap.statistics.annotation.SysLog;
import com.suncnpap.system.service.HolidayService;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


import com.app.util.beanutil.BeanUtil;
import com.app.util.common.Constants;
import com.app.util.common.DateUtil;
import com.app.util.common.HandlerResult;
import com.app.util.common.ResponseUtil;
import com.app.util.database.mybatis.Page;
import com.app.util.database.mybatis.QueryType;
import com.suncnpap.base.common.GlobaUser;
import com.suncnpap.base.common.ParamModel;
import com.suncnpap.base.controller.BaseController;

/** 
 * 说明：期刊Controller
 */
@Controller
@RequestMapping(value="/journal/circulate")
public class JournalCirculateController extends BaseController {
	
	//private static final Logger log = Logger.getLogger(JournalController.class);
	
	@Autowired
	JournalService journalService;
	
	@Autowired
	ReaderService readerService;
	
	@Autowired
	BorrowJournalService borrowJournalService;
	
	@Autowired
	BorrowJournalRecordService borrowJournalRecordService;
	
	@Autowired
	ReturnJournalService returnJournalService;
	
	@Autowired
	ReaderTypeService readerTypeService;
	
	@Autowired
	JournalRegistrationService journalRegistrationService;
	
	@Autowired
	HolidayService holidayService;
	
	@Autowired
	JournalTypeService journalTypeService;
	
	@RequestMapping(value="/getReader")
	public void getReader(@RequestBody Reader reader,HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strSchoolId = String.valueOf(result.get("strSchoolId"));
				reader = readerService.findByCardNumber(reader.getStrCardNumber(), strSchoolId);
				if(reader!=null){
					String strCardNumber = reader.getStrCardNumber();
					ReaderType readerType = readerTypeService.findById(reader.getStrReaderTypeId());
					
					Page page = new Page();
					page.addQueryAnd("br.strReaderCardNumber", strCardNumber);
					page.put("isOver", "true");
					page.setUsePage(false);
					page.addQueryAnd("lr.strSchoolId", result.get("strSchoolId"));
					page.addQueryAnd("l.strSchoolId", result.get("strSchoolId"));
					page.addQueryAnd("r.strSchoolId", result.get("strSchoolId"));
					List<BorrowJournalInfo> borrowJournalList = borrowJournalService.listInfo(page).getDataList();
					int intBorrow = borrowJournalList.size();
					int intNoBorrow = readerType.getIntNumOfJournal()-intBorrow;
					
					result.put("borrowJournalList", borrowJournalList);
					result.put("intBorrow", intBorrow);
					result.put("intNoBorrow", intNoBorrow);
					result.put("reader", reader);
				}else{
					result.setCode(1);
					result.setMessage("不存在的读者卡号");
				}
				
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	/**
	 * 列表页面数据处理，包括查询
	 * @param page
	 * @param response
	 */
	@RequestMapping(value="/list" )
	public void list(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		
		if (result.getCode()==0) {

			Page page = this.setPage();
			
			page.removeQueryAnd("strSchoolId");
			page.addQueryAnd("br.strSchoolId", GlobaUser.getStrSchoolId(request.getHeader("token")));
			
			page.put("user", "true");
			page.addQueryAnd("r.strSchoolId", result.get("strSchoolId"));
			
			String strUnitId = this.getParameter("strUnitId","");
			if(!strUnitId.equals("")){
				page.put("strUnitId", strUnitId);
				page.addQueryAnd("r.strUnitId", strUnitId);
			}
			
			String dtStartCreatDate = this.getParameter("dtStartCreatDate", "");
			if(!dtStartCreatDate.equals("")){
				page.addQueryAnd("br.dtCreatDate", QueryType.markGTEQ, dtStartCreatDate);
			}
			
			String dtEndCreatDate = this.getParameter("dtEndCreatDate", "");
			if(!dtEndCreatDate.equals("")){
				page.addQueryAnd("br.dtCreatDate", QueryType.markLTEQ, dtEndCreatDate);
			}
			
			String keyName = this.getParameter("keyName", "");
			String keywords = this.getParameter("keywords", "");
			if(!keyName.equals("")){
				if(keyName.equals("strJournalBarcode")){
					page.addQueryAnd("lr.strBarcodeNumber", QueryType.markLIKE, keywords);
				}else if(keyName.equals("strJournalTitle")){
					page.addQueryAnd("l.strJournalTitle", QueryType.markLIKE, keywords);
				}else if(keyName.equals("strUnifiedIssue")){
					page.addQueryAnd("l.strUnifiedIssue", QueryType.markLIKE, keywords);
				}else if(keyName.equals("strName")){
					page.addQueryAnd("r.strName", QueryType.markLIKE, keywords);
				}else if(keyName.equals("strCardNumber")){
					page.addQueryAnd("br.strReaderCardNumber", QueryType.markLIKE, keywords);
				}
			}
			
			
//			String strType = this.getParameter("strType","");
//			if(!strType.equals("")){
//				if(strType.equals("未还")){
//					page = borrowJournalService.listInfo(page);
//				}else if(strType.equals("已还")){
//					page.addQueryAnd("br.dtReturnDate", QueryType.MarkISNOTNULL,"");
//					page = borrowJournalRecordService.listInfo(page);
//				}
//			}else{
//				page.addQueryAnd("br.dtReturnDate", QueryType.MarkISNULL,"");
			page.addQueryAnd("lr.strSchoolId", result.get("strSchoolId"));
			page.addQueryAnd("l.strSchoolId", result.get("strSchoolId"));
			page.addQueryAnd("r.strSchoolId", result.get("strSchoolId"));
				page = borrowJournalRecordService.listInfo(page);
//			}
			result = this.returnPage(result, page);
			
		}
		
		ResponseUtil.writeJson(result, response);

	}
	
	/**
	 * 借阅处理
	 * @param obj
	 * @param response
	 */
	@RequestMapping(value="/borrowJournal",method=RequestMethod.POST)
	@SysLog(type=LogType.JOURNALBORROW)
	public void borrowJournal(@RequestBody BorrowJournal obj,HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strSchoolId = String.valueOf(result.get("strSchoolId"));
				
				JournalRegistration journalRegistration = journalRegistrationService.findByBarcode(obj.getStrJournalBarcode(), strSchoolId);
				if(journalRegistration!=null){
					
					BorrowJournal borrowJournal = borrowJournalService.findByJournalBarcode(obj.getStrJournalBarcode(), strSchoolId);
					
					if(borrowJournal==null){
						Reader reader = readerService.findByCardNumber(obj.getStrReaderCardNumber(), strSchoolId);
						
						Page page = new Page();
						page.addQueryAnd("strSchoolId", GlobaUser.getStrSchoolId(request.getHeader("token")));
						page.addQueryAnd("strStartTime", QueryType.markGTEQ, DateUtil.get(new Date(), "yyyy-MM-dd"));
						page.addQueryAnd("strEndTime", QueryType.markLTEQ, DateUtil.get(new Date(), "yyyy-MM-dd"));
						int count = holidayService.findCount(page);
						
						if(count>0){
							result.setMessage("假期内不能借书");
						}else{
							ReaderType readerType = readerTypeService.findById(reader.getStrReaderTypeId());
							
							Calendar cal = Calendar.getInstance();
							super.init(obj);
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
							obj.setDtBorrowDate(sdf.parse(sdf.format(cal.getTime())));
							
							Journal journal = journalService.findById(journalRegistration.getStrJournalId());
							JournalType journalType = journalTypeService.findById(journal.getStrType());
							int intBorrowingDays = 5;
							if(journalType!=null && journalType.getIntAvailableDays()!=null){
								intBorrowingDays = journalType.getIntAvailableDays();
							}
							cal.add(Calendar.DATE, intBorrowingDays);
							obj.setDtReturnDate(cal.getTime());
							borrowJournalService.add(obj);
							
							BorrowJournalRecord borrowJournalRecord = new BorrowJournalRecord();
							BeanUtil.copyBean(obj, borrowJournalRecord);
//							borrowJournalRecord.setDtReturnDate(null);
							borrowJournalRecord.setIsReturn(0);
							borrowJournalRecordService.add(borrowJournalRecord);
							
							journalRegistrationService.updateBorrowById(obj.getStrJournalBarcode(), result.get("strSchoolId")+"");
						
						}
					}else{
						result.setCode(1);
						result.setMessage("该期刊已经被借出");
					}
					
				}else{
					result.setCode(1);
					result.setMessage("不存在的期刊条码");
				}
				
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
	
	/**
	 * 归还处理
	 * @param obj
	 * @param response
	 */
	@RequestMapping(value="/returnJournal",method=RequestMethod.POST)
	@SysLog(type=LogType.RETURNJOURNAL)
	public void returnJournal(@RequestBody BorrowJournal obj,HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = this.checkToken(request);
		if (result.getCode()==0) {
			try{
				String strSchoolId = String.valueOf(result.get("strSchoolId"));
				
				BorrowJournalRecord borrowJournalRecord = borrowJournalRecordService.findByJournalBarcode(obj.getStrJournalBarcode(), strSchoolId);
				
				if(borrowJournalRecord!=null){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					borrowJournalRecord.setDtReturnDate(sdf.parse(sdf.format(new Date())));
					borrowJournalRecord.setIsReturn(1);
					borrowJournalRecordService.update(borrowJournalRecord);
					
					ReturnJournal returnTemp = new ReturnJournal();
					BeanUtil.copyBean(borrowJournalRecord, returnTemp);
					returnJournalService.add(returnTemp);
					
					borrowJournalService.deleteByJournalBarcode(obj.getStrJournalBarcode(), strSchoolId);
					
					journalRegistrationService.updateReturnById(obj.getStrJournalBarcode(), result.get("strSchoolId")+"");
					
					Reader reader = readerService.findByCardNumber(borrowJournalRecord.getStrReaderCardNumber(), strSchoolId);
					
					Page page = new Page();
					page.put("strReaderCardNumber", reader.getStrCardNumber());
					page.setUsePage(false);
					page.put("isOver", "true");
					page.addQueryAnd("lr.strSchoolId", result.get("strSchoolId"));
					page.addQueryAnd("l.strSchoolId", result.get("strSchoolId"));
					page.addQueryAnd("r.strSchoolId", result.get("strSchoolId"));
					List<BorrowJournalInfo> borrowJournalList = borrowJournalService.listInfo(page).getDataList();
					
					page = new Page();
					page.addQueryAnd("br.strId", borrowJournalRecord.getStrId());
					page.setUsePage(false);
					page.put("isOver", "true");
					page.addQueryAnd("lr.strSchoolId", result.get("strSchoolId"));
					page.addQueryAnd("l.strSchoolId", result.get("strSchoolId"));
					page.addQueryAnd("r.strSchoolId", result.get("strSchoolId"));
					List<BorrowJournalInfo> borrowBookRecordList = borrowJournalRecordService.listInfo(page).getDataList();
					
					result.put("borrowJournalList", borrowJournalList);
					result.put("borrowJournalRecord", borrowBookRecordList);
					result.put("reader", reader);
				}else{
					result.setCode(1);
					result.setMessage("该期刊没有被借阅");
				}
				
			}catch(Exception e){
				result.setCode(1);
				e.printStackTrace();
				throw e;
			}
		}
		ResponseUtil.writeJson(result, response);
	}
}
